package Point.FastSlow;

import 其他.DataStructure.ListNode;
import org.junit.Test;

/**
 * 链表+环 -> 快慢指针
 */
public class 环形链表II142 {
    public ListNode detectCycle(ListNode head) {
        if(head == null) return null;
        ListNode fast = head, slow =head;
        // 只有head一个节点 的 无环， 下面能判单head有环
        if(fast.next == null) return null;

        boolean haveCircle = false;
        while(fast!= null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                haveCircle = true;
                break;
            }
        }
        if(haveCircle){
            fast = head;
            while(fast!= slow){
                fast = fast.next;
                slow = slow.next;
            }
            return fast;
        }
        return null; // 无环 也就无环入口Node
    }

    @Test
    public void test(){
        /**
         *  1 2 3 4
         *    | _ |
         */
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l2;
        System.out.println("RES:" + detectCycle(l1).val);
    }
}
